<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Http\Requests\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function __construct() {
        $this->middleware('auth')->except(['show']);
    }

    public function show(User $user) {
        $topics = $user->topics()->paginate(5);
        return view('users.show', compact('user','topics'));
    }

    public function edit(User $user) {
        $this->authorize('update',$user);
        return view('users.edit', compact('user'));
    }

    public function update(UserRequest $request, ImageUploadHandler $upload, User $user) {
        $this->authorize('update',$user);
        $data = $request->all();
        if ($request->file('avatar')) {
            $res = $upload->save($request->file('avatar'), 'avatar', $user->id, 416);
            if ($res) {
                $data['avatar'] = $res['path'];
            }
        }
        $user->update($data);
        return redirect()->route('users.show', $user->id)->with('success', '用户信息更新成功');
    }
}
